package com.example.routes

import com.example.models.orderStorage
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Route.listOrderRoute() {
    // GET http://127.0.0.1:8080/order
    // Content-Type: application/json
    get("/order") {
        if (orderStorage.isNotEmpty()) call.respond(orderStorage)
    }
}

fun Route.getOrderRoute() {
    // GET http://127.0.0.1:8080/order/2020-04-06-01
    // Content-Type: application/json
    get("/order/{id?}") {
        val id = call.parameters["id"] ?: return@get call.respondText("Bad request", status = HttpStatusCode.BadRequest)
        val order = orderStorage.find { it.number == id } ?: return@get call.respondText(
            "Not found",
            status = HttpStatusCode.NotFound
        )
        call.respond(order)
    }
}

fun Route.totalOrderRoute() {
    //GET http://127.0.0.1:8080/order/2020-04-06-01/total
    //Content-Type: application/json
    get("/order/{id?}/total") {
        val id = call.parameters["id"] ?: return@get call.respondText("Bad request", status = HttpStatusCode.BadRequest)
        val order = orderStorage.find { it.number == id } ?: return@get call.respondText(
            "Not found",
            status = HttpStatusCode.NotFound
        )
        val total = order.contents.sumOf { it.price * it.amount }
        call.respond(total)
    }
}